//
//  NSObject+HDChatReplyManager.m
//  app
//
//  Created by D on 15/6/11.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HDChatReplyManager.h"
#import "HDChatReplyModel.h"

@interface HDChatReplyManager ()

@property (nonatomic,strong) NSMutableArray * mutableArray;
@property (nonatomic,strong) FMDatabaseQueue * fmdbQueue;

@end

@implementation HDChatReplyManager


+(HDChatReplyManager *)shareManager
{
    AS_SINGLETON(HDChatReplyManager, manager,{
        manager = [[HDChatReplyManager alloc]init];
        manager.mutableArray = [NSMutableArray array];
        HDAppDelegate * delegate = (HDAppDelegate*)[UIApplication sharedApplication].delegate;
        manager.fmdbQueue = delegate.fmdbQueue;
    })
    return manager;
}

-(NSMutableArray *)arrayFromChatReply
{
    NSMutableArray * arr1 = [NSMutableArray array];
    NSMutableArray * arr2 = [NSMutableArray array];
    
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        NSString* sql_one = @"select * from sqlite_master where name  = 'ChatReply';";
        if ([[db executeQuery:sql_one] next]){
            NSString * sql = @"select * from ChatReply;";
            FMResultSet * set = [db executeQuery:sql];
            [self.mutableArray removeAllObjects];
            while ([set next]) {
                
                NSString * msgid = [set stringForColumn:@"msgid"];
                NSString * title = [set stringForColumn:@"title"];
                NSString * uid = [set stringForColumn:@"uid"];
                NSString * forum = [set stringForColumn:@"forum"];
                NSString * card = [set stringForColumn:@"card"];
                NSString * name = [set stringForColumn:@"name"];
                NSString * content = [NSString stringWithFormat:@"[%@] 回复了您的帖子",name];
                NSString * face = [set stringForColumn:@"face"];
                NSString * time = [set stringForColumn:@"time"];
                
                
                NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys:msgid,@"msgid",title,@"title",uid,@"uid",forum,@"forum",card,@"card",content,@"content",face,@"face",name,@"name",time,@"time", nil];
                
                
                [arr1 addObject:dict];
            }
            
        }
        //[db close];
    }];
    //[self.fmdbQueue close];
    
    [arr2 addObjectsFromArray:arr1];

    NSSortDescriptor*sorter=[[NSSortDescriptor alloc]initWithKey:@"dateline" ascending:YES];
    NSMutableArray *sortDescriptors=[[NSMutableArray alloc]initWithObjects:&sorter count:1];
    NSArray *sortArray=[arr2 sortedArrayUsingDescriptors:sortDescriptors];
    
    for (int i=0; i<[sortArray count]; i++) {
        NSLog(@"排序后----->>%@",[[sortArray objectAtIndex:i] objectForKey:@"dateline"]);
        [self.mutableArray addObject:[HDChatReplyModel modelWithDict:[sortArray objectAtIndex:i]]];
    }
    
    return self.mutableArray;

    
}

@end
